#!/usr/bin/env python3
# coding: utf-8
# File: chatbot_graph.py
# Author: lhy<lhy_in_blcu@126.com,https://huangyong.github.io>
# Date: 18-10-4

from question_classifier import *
from question_parser import *
from answer_search import *

'''问答类'''


class ChatBotGraph:
    def __init__(self):
        self.classifier = QuestionClassifier()  # 问句类型分类
        self.parser = QuestionPaser()  # 问句解析
        self.searcher = AnswerSearcher()  # 数据库查询

    def chat_main(self, sent):
        answer = '您好，关于您的问题未检索到匹配结果，请您原谅。祝您身体棒棒！'
        res_classify = self.classifier.classify(sent)
        # 用于调试时打印
        print('question_classifier:\n', res_classify)
        ''' 
            到该步骤为止，假设问题是“怎样才能预防肾虚？”，
            res_classify={'args': {'肾虚': ['disease']}, 'question_types': ['disease_cause', 'disease_prevent']}
        '''
        if not res_classify:
            return answer
        res_sql = self.parser.parser_main(res_classify)
        # 用于调试时打印
        print('question_parser:\n', res_sql)
        '''
            到该步骤为止，
            res_sql = [
                {'question_type': 'disease_cause', 'sql': ["MATCH (m:Disease) where m.name = '肾虚' return m.name, m.cause"]},
                {'question_type': 'disease_prevent', 'sql': ["MATCH (m:Disease) where m.name = '肾虚' return m.name, m.prevent"]}]
        '''
        final_answers = self.searcher.search_main(res_sql)
        # 用于调试时打印
        print('search_sqler:\n', final_answers)
        if not final_answers:
            return answer
        else:
            # return '\n'.join(str(final_answers))
            return str(final_answers)

"""
    用于后端单独调试
"""
if __name__ == '__main__':
    handler = ChatBotGraph()
    while 1:
        question = input('用户:')
        print('\n')
        answer = handler.chat_main(question)
        print('\n')
        print('回复:', answer)
        print('\n')


"""
    用于前后端连接
"""
# from flask import Flask,request
# app = Flask(__name__)
# handler = ChatBotGraph()
# @app.route('/hello', methods = ["POST"])
# def hello_world():
# #这里面就是你想要返回给前端的值， 切记，这里只能返回字符串，如果是个json数据，你的通过json.dumps(你的json数据)
#     data = request.get_json()
#     print(data)
#     question = data['question']
#     print(question)
#     answer = handler.chat_main(question)
#     return answer
#
# if __name__ == '__main__':
#     # 这里host是你的后端地址，这里写0.0.0.0， 表示的是这个接口在任何服务器上都可以被访问的到，只需要前端访问该服务器地址就可以的，
#     # 当然你也可以写死，如222.222.222.222， 那么前端只能访问222.222.222.222, port是该接口的端口号,
#     # debug = True ,表示的是，调试模式，每次修改代码后不用重新启动服务
#     app.run(host='0.0.0.0', port=5000, debug=True)